<template>
  <div class="Player" v-show="playList.length >= 1">
    <!-- 全屏播放器  -->
    <transition name="slide">
      <div class="full-screen" v-show="fullScreen">
        <!-- 背景图 -->
        <div class="background">
          <img width="100%" height="100%" :src="imgsrc" />
        </div>
        <!-- 顶部 -->
        <div class="top">
          <div class="back" @click="back(false)">
            <i class="icon-back"></i>
          </div>
          <h1 class="title">{{ currentSong.name }}</h1>
          <h2 class="subtitle">
            <span v-for="item of currentSong.singer" :key="item.id">{{
              item.name
            }}</span>
          </h2>
        </div>
        <!-- 中部 -->
        <div class="middle">
          <!-- 图片 -->
          <div class="middle-l" ref="middle">
            <div class="cd-wrapper" ref="cdWrapper">
              <div class="cd">
                <img class="image" :src="imgsrc" :class="rorate" />
              </div>
            </div>
            <!-- 当前播放的歌词 -->
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{ playingLyric }}</div>
            </div>
          </div>
        </div>
        <!-- 底部 -->
        <div class="bottom">
          <!-- 左右切换分页显示 -->
          <!-- <div class="dot-wrapper">
            <span class="dot" :class="{ active: currentShow === 'cd' }"></span>
            <span
              class="dot"
              :class="{ active: currentShow === 'lyric' }"
            ></span>
          </div> -->
          <!-- 进度条 -->
          <div class="progress-wrapper">
            <span class="time time-l">{{ forMat(currentTime) }}</span>
            <div class="progress-bar-wrapper">
              <progress-bar :precent="precent" @precentChange="precentChange"></progress-bar>
            </div>
            <span class="time time-r">{{ forMat(currentSong.interval) }}</span>
          </div>
          <!-- icon图标操作区域 -->
          <div class="operators">
            <div class="icon icon-l">
              <i :class="iconMode" @click="changeMode"></i>
            </div>
            <div class="icon icon-l">
              <i class="icon-prev" @click="changeIndex(-1)"></i>
            </div>
            <div
              class="icon icon-center"
              :class="disabledCls"
              @click="changePlaying"
            >
              <i :class="playIcon"></i>
            </div>
            <div class="icon icon-r">
              <i class="icon-next" @click="changeIndex(1)"></i>
            </div>
            <div class="icon icon-r" @click="toggleFavorite(currentSong)">
              <i :class="getFavoriteIcon(currentSong)"></i>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <!-- 迷你播放器 -->
    <transition name="mini">
      <div
        class="mini-player"
        v-show="!fullScreen && currentSong != undefined"
        @click="back(true)"
      >
        <div class="icon">
          <img width="40" height="40" :src="imgsrc" :class="rorate" />
        </div>
        <div class="text">
          <h2 class="name">{{ currentSong.name }}</h2>
          <p class="desc">
            <span v-for="item of currentSong.singer" :key="item.id">{{
              item.name
            }}</span>
          </p>
        </div>
        <div class="control" @click.stop="changePlaying">
          <i :class="miniIcon"></i>
        </div>
        <div class="control">
          <i class="icon-playlist" @click.stop="showPlaysong"></i>
        </div>
      </div>
    </transition>

    <!-- 音频 -->
    <audio :src="audioSrc" ref="audio" @canplay="ready" @timeupdate="updateTime" @ended="end"></audio>
    <PlaySong ref="playSong"/>
  </div>
</template>

<script>
import ProgressBar from './ProgressBar'
import PlaySong from '@/components/base/PlaySong'
import { mapMutations, mapState } from 'vuex'

import { playerMixin } from '../../common/js/mixin'
import Lyric from 'lyric-parser'
export default {
  mixins: [playerMixin],
  components: {
    ProgressBar,
    PlaySong
  },
  data () {
    return {
      // 歌曲播放地址
      audioSrc: '',
      // 歌曲是在否准备
      songReady: false,
      // 播放模式
      playMode: {
        sequence: 0, // 顺序
        loop: 1, // 循环
        random: 2 // 随机
      },
      // 音频目前播放时间
      currentTime: 0,
      // 歌词对象
      currentLyric: null,
      // 当前播放那个的歌词行数
      currentLineNum: 0,
      // 当前播放的歌词
      playingLyric: '',
      // 当前展示的是歌词还是cd
      currentShow: 'cd',
      // 是否手指滑动状态
      touch: {}
    }
  },
  // 计算属性
  computed: {
    ...mapState([
      // 控制全屏
      'fullScreen',
      // 播放列表的数据是否存在
      'playList',
      // 当前播放歌曲
      'currentSong',
      // 播放状态
      'playing',
      // 当前歌曲索引
      'currentIndex',
      // 播放模式
      'mode',
      // 随机播放列表
      'sequenceList',
      // 播放历史
      'historyPlay',
      // 喜欢的歌曲
      'likeMusic'
    ]),
    imgsrc () {
      // 图片地址
      return JSON.stringify(this.currentSong) === '{}'
        ? ''
        : `https://y.gtimg.cn/music/photo_new/T002R300x300M000${this.currentSong.album.mid}.jpg`
    },
    miniIcon () {
      // mini播放器icon变化
      return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
    },
    playIcon () {
      // 播放暂停按钮
      return this.playing ? 'icon-pause' : 'icon-play'
    },
    // 当播放时候中间图片进行旋转
    rorate () {
      return this.playing ? 'play' : 'play pause'
    },
    // 播放模式图标
    iconMode () {
      return this.mode === this.playMode.sequence
        ? 'icon-sequence'
        : this.mode === this.playMode.loop
          ? 'icon-loop'
          : 'icon-random'
    },
    // 当歌曲未加载时候播放暂停按钮不可用
    disabledCls () {
      return this.songReady ? '' : 'disable'
    },
    // 计算当前播放时间与总时间的比例
    precent () {
      return this.currentTime / this.currentSong.interval
    }
  },
  methods: {
    ...mapMutations(['setFullScreen', 'setCurrentSong', 'setPlaying', 'setMode', 'setPlayList']),
    // 全屏/迷你播放器切换
    back (status) {
      this.setFullScreen(status)
    },
    // 获取播放地址
    async getAudioSrc (mid) {
      this.audioSrc = ''
      const { data: res } = await this.$http.get('/api/song/urls?id=' + mid)
      // 没有播放地址
      if (JSON.stringify(res.data) === {}) {
        this.audioSrc = ''
      } else {
        this.audioSrc = res.data[mid]
        // console.log(this.audioSrc)
      }
      if (this.audioSrc === undefined) {
        clearTimeout(this.timeAudio)
        this.timeAudio = setTimeout(() => {
          // 播放下一首
          this.changeIndex(1)
        }, 3000)
      }
    },
    // 获取歌词
    async getLyric (mid) {
      const { data: res } = await this.$http.get('/api/lyric?songmid=' + mid)
      // console.log(res)
      if (res.result === 100) {
        // res.data.lyric // 歌词数据
        this.currentLyric = new Lyric(res.data.lyric, this.handleLyric) // this.handleLyric回调函数
        this.currentLyric.play()
      } else {
        // 获取不到歌词清空
        this.currentLyric = null
        this.playingLyric = ''
        this.currentLineNum = 0
      }
    },
    // 处理歌词播放
    handleLyric ({ lineNum, txt }) {
      this.currentLineNum = lineNum
      // if (lineNum > 5) {
      //   let lineEl = this.$refs.lyricLine[lineNum - 5]
      //   this.$refs.lyricList.scrollToElement(lineEl, 1000)// 滚动到元素
      // } else {
      //   this.$refs.lyricList.scrollTo(0, 0, 1000)// 滚动到顶部
      // }
      this.playingLyric = txt
    },
    // 音频加载成功，可以播放
    ready () {
      this.songReady = true
      this.setPlaying(true)
      // 加载成功就可以播放
      this.$refs.audio.play()
    },
    // 音频加载错误
    error () {
      this.songReady = false
    },
    // 播放时间的变更
    updateTime (e) {
      this.currentTime = e.target.currentTime
    },
    // 音频播放结束
    end () {
      // 如果当前模式是循环播放
      if (this.mode === this.playMode.loop) {
        this.loop()
      } else {
        // 如果不是循环播放，则自动播放下一首
        this.changeIndex(1)
      }
    },
    // 时间的显示
    forMat (time) {
      time = time | 0
      const minute = time / 60 | 0
      const second = time % 60 | 0
      if (second < 10) return `${minute}:0${second}`
      return `${minute}:${second}`
    },
    // 拉动bar进度条后设置audio播放时间
    precentChange (precent) {
      // 重新设置拖动后的当前时间
      const currentTime = this.currentSong.interval * precent
      this.$refs.audio.currentTime = currentTime
      // 拉动bar进度条后歌词跟着进度条变化到和歌曲一样的
      if (this.currentLyric) {
        this.currentLyric.seek(currentTime * 1000)
      }
    },
    //  上一首下一首切换
    changeIndex (num) {
      if (this.playList.length === 1) {
        this.loop()
        // console.log('loop')
      } else {
        let index = this.currentIndex + num
        if (index < 0) index = this.playList.length
        // 如果播放结束 跳转到第一首
        if (index === this.playList.length) index = 0
        // 将修改的值存入vuex
        this.setCurrentIndex(index)
        // console.log(this.currentIndex)
      }
    },
    // 改变播放状态
    changePlaying () {
      //  已经是播放状态
      if (this.songReady) {
        this.playing ? this.setPlaying(false) : this.setPlaying(true)
        if (this.currentLyric) {
          // 歌词暂停与播放
          this.currentLyric.togglePlay()
        }
      }
    },
    // 切换播放模式
    changeMode () {
      const mode = (this.mode + 1) % 3
      this.setMode(mode)
      let list = null
      // 如果是随机播放模式
      if (mode === this.playMode.random) {
        this.shuffle(this.sequenceList)
        list = this.sequenceList
        // console.log('到这里还没有问题')
      } else {
        list = this.sequenceList
      }
      this.resetCurrentIndex(list)
      this.setPlayList(list)
    },
    loop () {
      this.$refs.audio.currentTime = 0
      this.$refs.audio.play()
      if (this.currentLyric) {
        this.currentLyric.seek(0)
      }
    },
    // 数组乱序
    shuffle (arr) {
      let i = arr.length
      while (i) {
        let j = Math.floor(Math.random() * i--);
        [arr[j], arr[i]] = [arr[i], arr[j]]
      }
      return arr
    },
    // playSong的显示与隐藏
    showPlaysong () {
      // console.dir(this.$refs.playSong)
      this.$refs.playSong.show()
      // this.$refs.playSong.hide()
    }
  },
  watch: {
    currentSong (newSong, oldSong) {
      // 歌曲改变进行本地存储
      if (this.currentSong === undefined) {
        this.setCurrentSong({})
        return
      }

      if (newSong.mid && newSong.mid === oldSong.mid) {
        return
      }

      // 获取歌曲地址
      this.getAudioSrc(this.currentSong.mid)
      // 防止歌词跳动
      if (this.currentLyric) {
        this.currentLyric.stop()
        this.currentLyric = null
        this.playingLyric = ''
        this.currentLineNum = 0
      }
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.getLyric(this.currentSong.mid)
      }, 1000)
      this.local(this.historyPlay, 'historyPlay')
    },
    //
    playing () {
      const audio = this.$refs.audio
      this.playing ? audio.play() : audio.pause()
    }
  }
}
</script>

<style lang="stylus" scoped>
@import "../../common/stylus/variable"
.slide-enter-active, .slide-leave-active {
  transition: all .4s;
  .top, .bottom {
    transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32);
  }
}
.slide-enter, .slide-leave-to{
  opacity: 0
  .top{
    transform: translateY(-100px);
  }
  .bottom{
    transform: translateY(100px);
  }
}
// 图片旋转
@keyframes rotate {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(360deg);
  }
}
.full-screen {
  position:fixed;
  top: 0;
  left:0;
  right: 0;
  bottom:0;
  z-index:99;
  background: $color-background;
  .background {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: -1;
    opacity: .6;
    filter: blur(20px);
  }
  .top {
    position: relative;
    .back {
      position: absolute;
      top:0;
      left:6px;
      .icon-back {
        display: block;
        font-size:20px;
        padding: 10px;
        transform: rotate(-90deg);
        color: $color-theme;
      }
    }
    .title {
      width: 70%;
      margin: 0 auto;
      font-size: 18px;
      text-align:center;
      line-height: 40px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .subtitle {
      display: flex;
      justify-content:center;
      font-size: 14px;
      line-height: 22px;
      span {
        padding: 0 5px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
  .middle {
    position: fixed;
    top: 120px;
    bottom: 170px;
    width: 100%;
    .middle-l {
      position: absolute;
      width: 100%;
      height: 0;
      padding-top: 80%;
      .cd-wrapper {
        position: absolute;
        left: 10%;
        top: 0;
        width: 80%;
        height: 100%;
        .cd {
          width: 100%;
          height: 100%;
          box-sizing: border-box;
          border: 10px solid rgba(255, 255, 255, 0.1);
          border-radius: 50%;
          .image {
            width 100%;
            height 100%;
            border-radius 50%;
          }
        }
        .play {
          animation: rotate 20s linear infinite;
        }
        .pause {
          animation-play-state: paused;
        }
      }
      .playing-lyric-wrapper {
        width: 80%;
        margin: 50px auto 0 auto;
        overflow: hidden;
        text-align: center;
        .playing-lyric {
          height: 20px;
          line-height: 20px;
          font-size: $font-size-medium;
          color: $color-text-l;
        }
      }
    }
  }
  .bottom {
    position: absolute;
    bottom: 50px;
    width: 100%;
    .dot-wrapper {
      text-align: center;
        .dot {
          display: inline-block;
          vertical-align: middle;
          margin: 0 4px;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: $color-text-l;
        }
    }
    .progress-wrapper {
      display flex;
      align-items center;
      width 80%;
      margin 0px auto;
      padding 10px 0;
      .time {
        color $color-text;
        font-size $font-size-small;
        flex 0 0 30px;
        line-height 30px;
        width 30px;
      }
      .time-l {
        text-align: left;
      }
      .time-r {
        text-align: right;
      }
      .progress-bar-wrapper {
        flex: 1;
      }
    }
    .operators {
      display flex;
      padding 0 20px;
      .icon {
        flex 1;
        text-align center;
        color $color-theme;
        font-size 30px;
        align-self center;
      }
      .icon-center {
        font-size 40px;
      }
      .disable {
        color: $color-theme-d;
      }
      .icon-favorite {
        color $color-sub-theme;
      }
    }
  }
}
.mini-player {
  display: flex;
  align-items:center;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 20;
  width: 100%;
  height: 60px;
  background: $color-highlight-background;
  .icon {
    flex: 0 0 40px;
    width: 40px;
    padding: 0 10px 0 20px;
    img {
      border-radius: 50%;
    }
    .play {
      animation: rotate 20s linear infinite;
    }
    .pause {
      animation-play-state: paused;
    }
  }
  .text {
    display: flex;
    flex-direction: column;
    justify-content: center;
    flex: 1;
    line-height: 20px;
    overflow: hidden;
    .name {
      margin-bottom: 2px;
      overflow:hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      font-size: $font-size-medium;
      color: $color-text;
    }
    .desc {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipse;
      font-size: $font-size-small;
      color: $color-text-d;
      span {
        margin-right 10px
      }
    }
  }
  .control {
    flex: 0 0 30px;
    width: 30px;
    padding: 0 10px;
  }
  .icon-play-mini, .icon-pause-mini, .icon-playlist {
    font-size: 30px;
    color: $color-theme-d;
  }
  .icon-mini {
    font-size: 32px;
    position: absolute;
    left: 0;
    top: 0;
  }
}
</style>
